<template>
  <div class="player"
       v-show="playlist.length"
  >

    <transition appear
                name="normal"
                @enter="enter"
                @after-enter="afterEnter"
                @leave="leave"
                @after-leave="afterLeave">
      <div class="normal-player"
           v-show="fullScreen"
      >
        <div class="background">
          <img :src="currentSong.pic">
        </div>
        <div class="top">
          <div
            class="back"
            @click="goBack"
          >
            <i class="icon-back"></i>
          </div>
          <h1 class="title">{{ currentSong.name }}</h1>
          <h2 class="subtitle">{{ currentSong.singer }}</h2>

        </div>
        <div class="middle"
             @touchstart.prevent="onMiddleTouchStart"
             @touchmove.prevent="onMiddleTouchMove"
             @touchend.prevent="onMiddleTouchEnd"
        >
          <div class="middle-l">

            <div
              ref="cdWrapperRef"
              class="cd-wrapper">
              <div
                class="cd"
                ref="cdRef"
              >
                <img
                  ref="cdImageRef"
                  class="image"
                  :src="currentSong.pic"/>

              </div>


            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{ playingLyric }}</div>
            </div>

          </div>
          <scroll
            class="middle-r"
            ref="lyricScrollRef"
            :style="middleRStyle">
            <div class="lyric-wrapper">
              <div v-if="currentLyric" ref="lyricListRef">
                <p class="text"
                   v-for="(line,index) in currentLyric.lines"
                   :key="line.num"
                   :class="{'current': currentLineNum ===index}"
                >

                  {{ line.txt }}
                </p>
              </div>
            </div>

          </scroll>

        </div>

        <div class="bottom">
          <div class="dot-wrapper">
            <span class="dot" :class="{'active': currentShow==='cd' }"></span>
            <span class="dot" :class="{'active':currentShow==='lyric'}"></span>
          </div>
          <div class="progress-wrapper">
            <span class="time time-l"> {{ formatTime(currentTime) }}</span>

            <progress-bar
              ref="barRef"
              :progress="progress"
            >
            </progress-bar>
            <span class="time time-r"> {{ formatTime(currentSong.duration) }}  </span>

          </div>
          <div class="operators">
            <div class="icon i-left">
              <i @click="changeMode" :class="modeIcon"></i>
            </div>
            <div class="icon i-left" :class="disableCls">
              <i @click="prev" class="icon-prev"></i>
            </div>
            <div class="icon i-center" :class="disableCls">
              <i @click="togglePlay" :class="playIcon"></i>
            </div>
            <div class="icon i-right" :class="disableCls">
              <i @click="next" class="icon-next"></i>
            </div>
            <div class="icon i-right">
              <i @click="toggleFavorite(currentSong)" :class="getFavoriteIcon(currentSong)"></i>
            </div>
          </div>
        </div>
      </div>

    </transition>
    <mini-player
      :progress="progress"
      :toggle-play="togglePlay"
    ></mini-player>
    <audio
      ref="audioRef"
      @pause="pause"
      @canplay="ready"
      @error="error"
      @timeupdate="updateTime"
      @ended="end"
    >
    </audio>
  </div>
</template>

<script>
import { useStore } from 'vuex'
import useLyric from './use-lyric'
import { computed, ref, watch } from 'vue'
import ProgressBar from './progress-bar'
import useMiddleInteractive from './use-middle-interactive'
import useMode from './use-mode'
import useFavorite from './use-favorite'
import { formatTime } from '@/assets/js/util'
import usePlayHistory from './use-play-history'
import Scroll from '../base/scroll/scroll'
import useAnimation from './user-animation'
import MiniPlayer from './mini-player'
export default {
  name: 'player',
  components: {
    Scroll,
    ProgressBar,
    MiniPlayer
  },

  setup() {
    const songReady = ref(false)
    const currentTime = ref(0)
    const audioRef = ref(null)
    let progressChanging = false
    //vuex
    const store = useStore()
    const playing = computed(() => store.state.playing)
    const playlist = computed(() => store.state.playlist)
    const fullScreen = computed(() => store.state.fullScreen)
    const currentSong = computed(() => store.getters.currentSong)
    const currentIndex = computed(() => store.state.currentIndex)
    const playIcon = computed(() => {
      return playing.value ? 'icon-pause' : 'icon-play'
    })
    const {
      getFavoriteIcon,
      toggleFavorite
    } = useFavorite()

    const { savePlay } = usePlayHistory()

    const {
      playingLyric,
      playLyric,
      stopLyric,
      currentLyric,
      currentLineNum
    }
      = useLyric({
      songReady,
      currentTime
    })

    const progress = computed(() => {
      console.log(currentSong.value.duration)
      return currentTime.value / currentSong.value.duration
    })
    const disableCls = computed(() => {
      return songReady.value ? '' : 'disable'
    })

    const {
      currentShow,
      middleLStyle,
      middleRStyle,
      onMiddleTouchStart,
      onMiddleTouchMove,
      onMiddleTouchEnd
    } = useMiddleInteractive()
    const {
      modeIcon,
      modeText,
      changeMode
    } = useMode()

    function goBack() {
      store.commit('setFullScreen', false)
    }

    function error() {
      songReady.value = true
    }

    function pause() {
      store.commit('setPlayingState', false)
    }

    function ready() {
      if (songReady.value) {
        return
      }
      songReady.value = true
      playLyric()
      savePlay(currentSong.value)
    }

    function togglePlay() {
      debugger
      if (!songReady.value) {
        return
      }
      store.commit('setPlayingState', !playing.value)
    }

    function prev() {
      const list = playlist.value
      if (!songReady.value || !list.length) {
        return
      }
      if (list.length == 1) {
        loop()
      } else {
        let index = currentIndex - 1
        if (index === -1) {
          index = list.length - 1
        }

        store.commit('setCurrentIndex', index)
      }

    }

    function next() {
      const list = playlist.value
      if (!songReady.value || !list.length) {
        return
      }

      if (list.length === 1) {
        loop()
      } else {
        let index = currentIndex.value + 1
        if (index === list.length) {
          index = 0
        }
        store.commit('setCurrentIndex', index)
      }
    }

    function loop() {
      const audioEl = audioRef.value
      audioEl.currentTime = 0
      audioEl.play()
      store.commit('setPlayingState', true)
    }

    function updateTime(e) {
      if (!progressChanging) {
        currentTime.value = e.target.currentTime
      }
    }

    watch(currentSong, (newSong) => {
      if (!newSong.id || !newSong.url) {
        return
      }
      currentTime.value = 0
      songReady.value = false
      const audioEl = audioRef.value
      audioEl.src = newSong.url
      audioEl.play()
      store.commit('setPlayingState', true)

    })

    watch(playing, (newPlaying) => {
      if (!songReady.value) {
        return
      }
      const audioEl = audioRef.value
      if (newPlaying) {
        audioEl.play()
        playLyric()
      } else {
        audioEl.pause()
        stopLyric()
      }
    })
    //获取动画
    const { enter, afterLeave, afterEnter, leave, cdWrapperRef } = useAnimation()

    return {
      audioRef,
      playlist,
      fullScreen,
      currentSong,
      goBack,
      playingLyric,
      currentShow,
      modeIcon,
      disableCls,
      getFavoriteIcon,
      toggleFavorite,
      playIcon,
      formatTime,
      error,
      ready,
      playLyric,
      savePlay,
      pause,
      stopLyric,
      togglePlay,
      changeMode,
      prev,
      next,
      progress,
      updateTime,
      currentTime,
      currentLyric,
      currentLineNum,
      middleLStyle,
      middleRStyle,
      onMiddleTouchStart,
      onMiddleTouchMove,
      onMiddleTouchEnd,
      enter,
      afterLeave,
      afterEnter,
      leave,
      cdWrapperRef
    }

  }
}
</script>

<style lang="scss" scoped>
.player {
  .normal-player {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 150;
    background: $color-background;

    .background {
      position: absolute;
      left: 0;
      right: 0;
      width: 100%;
      height: 100%;
      opacity: 0.6;
      filter: blur(20px);
      z-index: -1;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .top {
      position: relative;

      .back {
        position: absolute;
        left: 6px;
        top: 0;
        z-index: 50;

        .icon-back {
          display: block;
          padding: 9px;
          font-size: $font-size-large-x;
          color: $color-theme;
          transform: rotate(-90deg);
        }
      }

      .title {
        width: 70%;
        line-height: 40px;
        margin: 0 auto;
        font-size: $font-size-large;
        color: $color-text;
        text-align: center;
      }

      .subtitle {
        line-height: 20px;
        text-align: center;
      }
    }

    .middle {
      position: fixed;
      width: 100%;
      top: 80px;
      bottom: 170px;
      white-space: nowrap;

      .middle-l {
        width: 100%;
        height: 0;
        padding-top: 80%;
        display: inline-block;
        position: relative;

        .cd-wrapper {
          position: absolute;
          top: 0;
          left: 10%;
          width: 80%;
          box-sizing: border-box;
          height: 100%;

          .cd {
            width: 100%;
            height: 100%;
            border-radius: 50%;

            img {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              box-sizing: border-box;
              border-radius: 50%;
              border: 10px solid rgba(255, 255, 255, 0.1);
            }
          }
        }

        .playing-lyric-wrapper {
          width: 80%;
          margin: 30px auto 0 auto;
          overflow: hidden;
          text-align: center;

          .playing-lyric {
            height: 20px;
            line-height: 20px;
            font-size: $font-size-medium;
            color: $color-text-l;
          }
        }
      }

      .middle-r {
        display: inline-block;
        width: 100%;
        height: 100%;
        overflow: hidden;
        vertical-align: top;
      }
    }

    .bottom {
      position: absolute;
      bottom: 50px;
      width: 100%;

      .dot-wrapper {
        text-align: center;

        .dot {
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: $color-text-l;
          margin: 0 4px;

          &.active {
            width: 20px;
            border-radius: 5px;
            background: $color-text-ll;
          }
        }
      }

      .progress-wrapper {
        display: flex;
        width: 80%;
        align-items: center;
        margin: 0px auto;
        padding: 10px 0;

        .time {
          flex: 0 0 40px;
          line-height: 30px;
          width: 40px;
          color: $color-text;
          font-size: $font-size-small;

          &.time-l {
            text-align: left;
          }

          &.time-r {
            text-align: right;
          }
        }
      }

      .operators {
        display: flex;
        align-items: center;

        .icon {
          flex: 1;
          color: $color-theme;

          &.disable {
            color: $color-theme-d;
          }

        }

        .i-left {
          text-align: right;
        }

        i {
          font-size: 30px;
        }

        .i-center {
          padding: 0 20px;
          text-align: center;

          i {
            font-size: 40px;
          }
        }
      }
    }
  }

}

</style>
